package remote

import (
	"errors"
	"fmt"
	"time"
)

// Execute 这里应该要处理session断开的流程吧
func (n *Client) Execute(cmd string) (string, error) {
	return n.ExecuteIn(cmd, -1)
}

// ExecuteIn 这里应该要处理session断开的流程吧
func (n *Client) ExecuteIn(cmd string, timeout int) (string, error) {
	fmt.Printf("Run: %s\n", cmd)
	if n.client == nil {
		err := n.Connect(timeout)
		if err != nil {
			return "", err
		}
	}
	session, err := n.client.NewSession()
	if err != nil {
		fmt.Printf("NewSession fail: %v\n", err)
		return "", err
	}
	defer session.Close()
	if timeout > 0 {
		timer := time.AfterFunc(time.Duration(timeout)*time.Second, func() {
			session.Close()
		})
		defer timer.Stop()
	}
	buf, err := session.CombinedOutput(cmd)
	n.LastResult = string(buf)
	fmt.Printf("out: %v\n", n.LastResult)
	if err != nil {
		err = errors.New(fmt.Sprintf("%s;\n%s\n", err.Error(), n.LastResult))
	}
	return n.LastResult, err
}
